package com.yc.vcode.web;

import com.google.gson.Gson;
import com.yc.vcode.bean.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VcodeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final Object svcode = request.getSession().getAttribute("vcode");
        final Long vcodeTimeout = (Long) request.getSession().getAttribute("vcodeTimeout");
        final String rvcode = request.getParameter("vcode");
        Result res = null;
        if(svcode == null){
            res = new Result(-1, "请先获取验证码!",null);
        } else if(rvcode == null){
            res = new Result(-2, "请输入验证码!",null);
        } else if(rvcode.equalsIgnoreCase(svcode.toString()) == false){
            res = new Result(-3, "请输入正确的验证码!",null);
        } else if( vcodeTimeout < System.currentTimeMillis()){
            request.getSession().removeAttribute("vcode");
            request.getSession().removeAttribute("vcodeTimeout");
            res = new Result(-4, "验证码超时!",null);
        }
        if(res != null){
            response.setContentType("application/json;charset=utf-8");
            final String json = new Gson().toJson(res);
            response.getWriter().println(json);
            return false;
        }
        // 验证码验证通过不代表业务流程正常通过, 所以保留验证码
        //request.getSession().removeAttribute("vcode");
        return true;
    }
}
